package rest.jbpm.history;

import java.util.List;
import org.hibernate.*;
import org.jbpm.api.cmd.*;
import org.slf4j.*;
import org.jbpm.pvm.internal.history.model.HistoryProcessInstanceImpl;
import org.jbpm.pvm.internal.util.CollectionUtil;


/**
 * Create command to find all(or range) processes in witch specific user was
 * taking place.
 * 
 * @author Serge Petrunin
 * 
 */

public class RecentProcessesByUserCmd implements 
        Command<List<HistoryProcessInstanceImpl>> {
    
    private static final Logger log = LoggerFactory.getLogger(RecentProcessesByUserCmd.class);

	/**
	 * Thus Command interface implements Serializable
	 */
	private static final long serialVersionUID = -805274700231862L;

	private final String userId;
	private final int limits;
	private final static String hql = 
    "SELECT process FROM org.jbpm.pvm.internal.history.model.HistoryProcessInstanceImpl process, "
  + "org.jbpm.pvm.internal.history.model.HistoryTaskImpl task "
  + "JOIN FETCH process.historyVariables as variables "
  + "WHERE task.executionId = process.processInstanceId AND task.assignee=:name "
  + "ORDER BY process.startTime DESC";

	public RecentProcessesByUserCmd(String userId, int limits) {
		this.userId = userId;
		this.limits = limits;
	}

	@Override
	public List<HistoryProcessInstanceImpl> execute(Environment environment)
			throws Exception {
        
        Session session = null;
        SessionFactory sessionFactory = environment.get(SessionFactory.class);
        try {
            
            session = sessionFactory.openSession();
            Query query = session.createQuery(hql);
            query.setParameter("name", userId);
            query.setFirstResult(0);
            query.setMaxResults(limits);
            return CollectionUtil.checkList(query.list(), HistoryProcessInstanceImpl.class);
            
        } finally {
            if(session != null) session.close();
        }
	}

}
